using System.Reflection;
using AvaloniaApplication1.Factory;
using Microsoft.Extensions.DependencyInjection;

namespace AvaloniaApplication1.Service;

/// <summary>
/// 拓展方法，利用反射获取所有实现 IViewModelFactory 的类，并注册到 DI 容器中
/// </summary>
public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddViewModelFactories(this IServiceCollection services)
    {
        // 找到泛型接口 IViewModelFactory<TModel, TViewModel>
        var factoryInterfaceType = typeof(IViewModelFactory<,>);
        var assembly = Assembly.GetExecutingAssembly();

        foreach (var type in assembly.GetTypes())
        {
            if (!type.IsClass || type.IsAbstract) continue;

            var interfaces = type.GetInterfaces();
            foreach (var implementedInterface in interfaces)
            {
                // 判断是否实现了 IViewModelFactory 接口
                if (implementedInterface.IsGenericType && implementedInterface.GetGenericTypeDefinition() == factoryInterfaceType)
                {
                    // 将实现注册到 DI 容器中 services.AddSingleton<IViewModelFactory<DeviceCardModel, DeviceCardViewModel>,DeviceCardViewModelFactory>();
                    services.AddSingleton(implementedInterface, type);
                    break;
                }
            }
        }

        return services;
    }
}